package com.example.administrator.printoutindemo;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;


import com.example.administrator.printoutindemo.services.Tools;
import com.example.administrator.printoutindemo.services.dyjApplication;
import com.example.administrator.printoutindemo.zxing.activity.CaptureActivity;


import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;


public class StoreListOutStorage extends Activity {

	private Button s_out_btn_qrccode = null;
	private TextView s_out_pwd = null;
	private TextView s_out_txt_lqr = null;

	List<OutStorageListMaterialInfo> li = null;
	OutStorageListMaterialInfo omi = null;

	private StoreListOutStorageListAdapter adapter = null;
	private ListView s_out_store_listView = null;

	String pwd = "";
	String scanResult = "";

	private static final String WEBSERVICE_CONFIG = "webServiceInfo";
	private static final int LOGINSUCCESS = 0;
	private static final int NETWORKERROR = 2;
	private static final int SYSERROR = 3;
	private static final int READSUCCESS = 4;
	private static final int UPEROOR = 5;
	ProgressDialog progressDiaog;

	private final Handler hanlder = new Handler() {
		public void handleMessage(android.os.Message msg) {

			switch (msg.what) {
				case LOGINSUCCESS:

					s_out_pwd.setText(pwd);
					adapter.setList(li);
					s_out_store_listView.setAdapter(adapter);

					progressDiaog.dismiss();
					break;
				case READSUCCESS:

					Intent listIntent1 = new Intent();
					listIntent1.setClass(StoreListOutStorage.this,
							StoreListOutStorage.class);
					startActivity(listIntent1);
					Toast.makeText(StoreListOutStorage.this, "出库成功!",
							Toast.LENGTH_LONG).show();
					break;
				case NETWORKERROR:

					Toast.makeText(StoreListOutStorage.this, "网络或系统异常!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;
				case SYSERROR:

					Toast.makeText(StoreListOutStorage.this, "出库失败!",
							Toast.LENGTH_LONG).show();
					progressDiaog.dismiss();
					break;

				default:
					progressDiaog.dismiss();
					break;
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.store_activity_listoutstorage);

		s_out_btn_qrccode = (Button) findViewById(R.id.s_out_btn_qrccode);
		s_out_pwd = (TextView) findViewById(R.id.s_out_pwd);
		s_out_txt_lqr = (TextView) findViewById(R.id.s_out_txt_lqr);

		String user_name = ((dyjApplication) getApplication()).get_user_name();
		s_out_txt_lqr.setText(user_name);
		s_out_store_listView = (ListView) findViewById(R.id.s_out_store_listView);

		omi = new OutStorageListMaterialInfo(this);
		adapter = new StoreListOutStorageListAdapter(this);

		final String user_login = ((dyjApplication) getApplication())
				.get_user_login();
		final String user_pwd = ((dyjApplication) getApplication())
				.get_user_pwd();
		final int user_id = ((dyjApplication) getApplication()).get_user_id();

		s_out_btn_qrccode.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// TODO Auto-generated method stub
				Intent openCameraIntent = new Intent(StoreListOutStorage.this,
						CaptureActivity.class);
				startActivityForResult(openCameraIntent, 0);
			}
		});

		if (user_id != 0) {

			progressDiaog = new ProgressDialog(StoreListOutStorage.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();
			new Thread(new Runnable() {

				@Override
				public void run() {

					try {
						pwd = callWebServiceGetPwd(user_login, user_pwd);
						li = GetOutListInfoFromWebService(user_login);

						if (!pwd.equals("")) {
							Message m = new Message();
							m.what = StoreListOutStorage.LOGINSUCCESS;
							hanlder.sendMessage(m);
						}

					} catch (Exception e) {
						Message m = new Message();
						m.what = StoreListOutStorage.SYSERROR;
						hanlder.sendMessage(m);
					}

				}
			}).start();
		} else {
			Tools.showDialogInfo(this, "登录已过期，请重新登录");
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);

		if (resultCode == RESULT_OK) {
			Bundle bundle = data.getExtras();
			scanResult = bundle.getString("result");
			// lbl_QRCode.setText(scanResult);

			progressDiaog = new ProgressDialog(StoreListOutStorage.this);
			progressDiaog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置为圆形进度条
			progressDiaog.setTitle("提示");
			// progressDiaog.setIcon(R.drawable.ic_launcher);//设置进度条的图标
			progressDiaog.setMessage("系统正在努力与服务器联系，请稍后......");
			progressDiaog.setIndeterminate(false);// 设置进度条不明确
			progressDiaog.setCancelable(true);

			progressDiaog.show();

			new Thread() {
				@Override
				public void run() {

					String user_login = ((dyjApplication) getApplication())
							.get_user_login();

					li = GetOutListInfoFromWebService(user_login);

					if (!scanResult.equals("")) {
						String r = callWebServiceOutStorage(scanResult,user_login);

						if (r.equals("1") && li.size() > 0) {
							Message m = new Message();
							m.what = StoreListOutStorage.READSUCCESS;
							hanlder.sendMessage(m);
						}
						else {
							Message m = new Message();
							m.what = StoreListOutStorage.SYSERROR;
							hanlder.sendMessage(m);
						}
					}

				}
			}.start();

		}
	}

	// 获取开门密码
	private String callWebServiceGetPwd(String user_login, String user_pwd) {

		String result = "";

		try {

			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "GetPwd";
			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";

			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("user_login", user_login);
			request.addProperty("user_pass", user_pwd);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				// if ("1".equals(response.toString())) {
				String t = response.toString();

				if (!t.equals("")) {
					result = t;
				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			// TODO: handle exception
			progressDiaog.dismiss();
		}

		return result;
	}

	// 获取出库记录信息
	private List<OutStorageListMaterialInfo> GetOutListInfoFromWebService(
			String loginName) {

		List<OutStorageListMaterialInfo> list = null;
		try {
			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "GetListOutStorageListByAPPLoginName";

			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";
			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("loginName", loginName);
			// request.addProperty("pass", edtPwd.getText().toString());
			// request.addProperty("sYardCode", "WLY");

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

				String returnStr = response.toString();

				if ("" != returnStr) {
					returnStr = returnStr.substring(returnStr.lastIndexOf("["),
							returnStr.length());

					returnStr = returnStr.replace("\\", "");

					list = omi.getListFromJSON(returnStr);

				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			e.printStackTrace();
		}

		return list;
	}

	// 出库
	private String callWebServiceOutStorage(String mid, String loginName) {

		String result = "";

		try {

			/****************** 调用webService ***********************/
			// 调用.net 的WebService.
			String nameSpace = "http://dyjapp.org/";
			String methodName = "UpdateOutStorageByQRCMid";
			SharedPreferences sPreferencces = getSharedPreferences(
					WEBSERVICE_CONFIG, 0);

			String url = "http://" + sPreferencces.getString("ip", "") + ":"
					+ sPreferencces.getString("Port", "")
					+ "/StoreService.asmx";

			String soapAction = nameSpace + methodName;

			// 设置连接参数
			SoapObject request = new SoapObject(nameSpace, methodName);

			// 增加属性参数。 将相关的函数参数放入到过程中。
			request.addProperty("mid", mid);
			request.addProperty("loginName", loginName);

			SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
					SoapEnvelope.VER11);// soap协议版本必须用SoapEnvelope.VER11（Soap
			// V1.1）;

			// 注意：这个属性是对dotnetwebservice协议的支持,如果dotnet的webservice
			// 不指定rpc方式则用true否则要用false
			envelope.dotNet = true;

			// envelope.setOutputSoapObject(request);//设置请求参数
			envelope.bodyOut = request; // enveloper.bodyOut=request 与
			// envelope.setOutputSoapObject(request)
			// 效果相同。
			// step4 创建HttpTransportSE对象
			HttpTransportSE ht = new HttpTransportSE(url);
			// step5 调用WebService
			ht.call(soapAction, envelope); // 关键的一步，很多问题都在这一步调试时出现问题。要么是IIS有问题，要么是ksoap2相关参数没配置好。
			if (envelope.getResponse() != null) {
				SoapPrimitive response = (SoapPrimitive) envelope.getResponse();
				// if ("1".equals(response.toString())) {
				String t = response.toString();

				if (!t.equals("")) {
					result = t;
				}

			}
			/****************** 调用webService结束 ***********************/

		} catch (Exception e) {
			// TODO: handle exception
			progressDiaog.dismiss();
		}

		return result;
	}

}